package org.example.gradleDemo.lists;

import org.example.gradleDemo.jmh.Trade;

import java.util.LinkedHashMap;
import java.util.Map;

public final class LinkedMapDemo {
    private final LinkedHashMap<Long, Trade> _tradeMap = new LinkedHashMap();

    public Trade Last;

    public LinkedMapDemo() {
        Last = null;
    }

    public void Add(final Trade trade) {
        _tradeMap.put(trade.id(), trade);
        if (_tradeMap.size() > 1) {
            Last = trade;
        }
    }

    public Trade getFirst() {
        return _tradeMap.isEmpty() ? null : _tradeMap.entrySet().iterator().next().getValue();
    }

    public Trade getSecond() {
        if (_tradeMap.size() < 2) {
            return null;
        }
        if (this.Last != null) return this.Last;

        int i = 1;
        for (Map.Entry<Long, Trade> entry : _tradeMap.entrySet()) {
            if (i == 2) {
                Last = entry.getValue();
                break;
            }
            i++;
        }
        return Last;
    }

    public Trade getPreviousLast() {
        final int size = _tradeMap.size();
        if (size < 2) {
            return null;
        }
        int i = size;
        Trade trade = null;
        for (Map.Entry<Long, Trade> entry : _tradeMap.entrySet()) {
            if (i == size - 2) {
                trade = entry.getValue();
                break;
            }
            i--;
        }
        return trade;

    }

    public void Remove(final Long tradeId) {
        _tradeMap.remove(tradeId);
        if (this.Last != null && this.Last.id() == tradeId.longValue()) {
            this.Last = null;
        }
    }
}
